//这个程序是用来测试多进程同步问题

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
#include <arpa/inet.h>
#include <pthread.h>
#include <vector>

#define PORT 8888
#define IP "127.0.0.1"

void *handler(void *argv)
{
	int time = 10;

	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0)
	{
		perror("sockfd");
		pthread_exit((void *)1);
	}

	struct sockaddr_in peer;
	bzero(&peer, sizeof(peer));
	peer.sin_family = AF_INET;
	peer.sin_addr.s_addr = inet_addr(IP);
	peer.sin_port = htons(PORT);

	int n = connect(sockfd, (struct sockaddr *)&peer, sizeof(peer));
	if (n < 0)
	{
		perror("connect");
		close(sockfd); // Cleanup
		pthread_exit((void *)1);
	}

	while (time--)
	{
		std::string buffer = "hello";
		sleep(1);
		int n=::send(sockfd, buffer.c_str(), buffer.size(), MSG_DONTWAIT);
		if(n<=0) break;
	}

	close(sockfd); // Cleanup
	pthread_exit(nullptr);
}

int main(int argc, char *argv[])
{
	if (argc != 2)
	{
		std::cout<<"Usage:\n\t"<<argv[0]<<" thread_num"<<std::endl;
		return 0;
	}
	int max = std::stoi(argv[1]);
	std::vector<pthread_t> v;
	for (int i = 0; i < max; i++)
	{
		pthread_t thread_id;
		int n = pthread_create(&thread_id, nullptr, handler, nullptr);
		if (n < 0)
		{
			perror("thread create");
			return 1;
		}
		v.emplace_back(thread_id);
	}
	for (auto e : v)
	{
		std::cout << "wait " << e << std::endl;
		pthread_join(e, 0);
	}
	return 0;
}
